﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MoroMoro.Samples.ToDoList.Base.Application;
using MoroMoro.Samples.ToDoList.Application;
using MoroMoro.Samples.ToDoList.Domain.ToDos;
using MoroMoro.Samples.ToDoList.Presentation.Views.ToDos;
using MoroMoro.Samples.ToDoList.Presentation.ErrorMessages;

namespace MoroMoro.Samples.ToDoList.Presentation.Presenters.ToDos
{
    /// <summary>
    /// ToDo 編集プレゼンターです。
    /// </summary>
    public sealed class ToDoEditionPresenter : ToDoBuildPresenter<IToDoEditionView, EntityEditionErrors>
    {
        /// <summary>
        /// <see cref="ToDoEditionPresenter"/> クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="view">ビュー。</param>
        /// <param name="facade">ファサード。</param>
        /// <param name="target">編集対象の ToDo。</param>
        /// <exception cref="System.ArgumentNullException">view または facade または target が null です。</exception>
        public ToDoEditionPresenter(IToDoEditionView view, ToDoListFacade facade, ToDo target)
            : base(view, facade, facade.CreateToDoBuilder(target))
        {
        }


        /// <inheritdoc/>
        protected override void OnLoad(object sender, EventArgs e)
        {
            base.OnLoad(sender, e);

            View.Title = Builder.Title;
            View.Category = Builder.Category;
            var memoBuilders = Builder.MemoBuilders;
            for (int i = 0; i < memoBuilders.Count(); i++)
            {
                var memoBuilder = memoBuilders.ElementAt(i);
                View.AddMemoArea(OnMemoTextChanged);
                View.SetMemoText(i, memoBuilder.Text);
            }
        }

        /// <inheritdoc/>
        protected override void ExecuteBuild(Action<EntityEditionErrors> errorHandler)
        {
            Facade.ExecuteToDoEdition(Builder, errorHandler);
        }

        /// <inheritdoc/>
        protected override string CreateErrorMessage(EntityEditionErrors error)
        {
            var errorMessage = new EntityEditionErrorMessage();
            error.HandledBy(errorMessage);
            return errorMessage.ToString();
        }
    }
}
